import { defineStore } from 'pinia'

export interface UserInfo {
  id?: string
  name?: string
  role?: 'admin' | 'partner'
  loginId?: string
  email?: string
}

export const useAuthStore = defineStore('KoreanFakeAdminAuth', {
  state: () => ({
    token: '' as string,
    user: {} as UserInfo,
  }),
  persist: {
    key: 'admin_auth'
  },
  getters: {
    isLoggedIn: (state) => !!state.token,
    isAdmin: (state) => state.user.role === 'admin',
    isPartner: (state) => state.user.role === 'partner',
    canAccessFinance: (state) => state.user.role === 'admin',
    canAccessSystemSettings: (state) => state.user.role === 'admin',
    canManagePartners: (state) => state.user.role === 'admin',
  },
  actions: {
    setToken(token: string) {
      this.token = token
    },
    clear() {
      this.token = ''
      this.user = {}
    },
    async checkAuth() {
      if (!this.token) return false

      try {
        const API_BASE_URL = (import.meta as any)?.env?.VITE_API_BASE_URL || ''
        const response = await fetch(`${API_BASE_URL}/api/auth/me`, {
          credentials: 'include',
        })

        if (!response.ok) {
          this.clear()
          return false
        }

        const userInfo = await response.json()

        if (userInfo.role !== 'admin' && userInfo.role !== 'partner') {
          this.clear()
          return false
        }

        this.user = {
          id: userInfo.id,
          name: userInfo.name || userInfo.nickname || userInfo.loginId,
          role: userInfo.role,
          loginId: userInfo.loginId,
          email: userInfo.email,
        }

        return true
      } catch (error) {
        console.error('检查认证状态失败:', error)
        this.clear()
        return false
      }
    },
    async logout() {
      try {
        const API_BASE_URL = (import.meta as any)?.env?.VITE_API_BASE_URL || ''
        await fetch(`${API_BASE_URL}/api/auth/logout`, {
          method: 'POST',
          credentials: 'include',
        })
      } catch (error) {
        console.error('退出登录失败:', error)
      } finally {
        this.clear()
      }
    },
  },
})

